<template>
    <div class="container">
        <h3>原料入库</h3>
        <el-tabs v-model="activeName" type="border-card" style="margin-top:20px;" @tab-click="handleClick">
            <el-tab-pane label="中药材" name="中药材" >
                <el-row style="margin: 10px 0 20px 0">
                    <el-col :span="7">
                        <el-input placeholder="请输入关键词" style="width:300px" v-model.trim="searchName1">
                            <i slot="prefix" class="el-input__icon el-icon-search"></i>
                            <el-button slot="append" @click="handleSearch1">搜索</el-button>
                        </el-input>
                    </el-col>
                    <router-link :to="{path:'/materialCheck/addMaterialCheck',query: {type: '中药材'}}"><el-button type="primary" v-if="added" style="float:right; margin-right: 10px">添加原料</el-button></router-link>
					<el-button style="float:right; margin-right: 10px" @click="download">导出数据</el-button>
                </el-row>

                <el-table
                    :data="tableData"
                    border
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                >
                    <el-table-column prop="breedName" sortable label="名称"></el-table-column>
                    <el-table-column prop="inType" sortable label="入库类型"></el-table-column>
                    <el-table-column prop="inBatch" sortable label="进厂编号"></el-table-column>
                    <el-table-column prop="totalNum" sortable label="入库数量">
                        <template slot-scope="scope">
                            {{scope.row.totalNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="surplusNum" sortable label="剩余数量">
                        <template slot-scope="scope">
                            {{scope.row.surplusNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="lossNum" sortable label="报损数量">
                        <template slot-scope="scope">
                            {{scope.row.lossNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                     <el-table-column prop="car" sortable label="质量标准"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                v-if="check"
                                @click="handleView(scope.$index, scope.row)"
                            >查看</el-button>
                            <el-button type="text" v-if="scope.row.isRecall == 0">
                                <el-dropdown style="color: #409EFF; font-size:12px">
                                    <span class="el-dropdown-link">
                                        更多
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item>
                                            <el-button
                                                type="text"
                                                v-if="check1"
                                                @click="handleEdit(scope.$index, scope.row)"
                                                style="color: #666"
                                            >编辑</el-button>
                                        </el-dropdown-item>
										<el-dropdown-item>
										    <el-button
										        type="text"
										        @click="handleadd(scope.$index, scope.row)"
										        style="color: #666"
										    >新增入库</el-button>
										</el-dropdown-item>
                                        <el-dropdown-item>
                                            <el-button
                                                type="text"
                                                v-if="check2"
                                                @click="handleFrmLoss(scope.$index, scope.row)"
                                                style="color: #666"
                                            >报损</el-button>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </el-button>
                            <el-button
                                v-if="scope.row.isRecall == 1"
                                type="info"
                                disabled
                            >已召回</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize1" @current-change="handleCurrentChange1" :total="total1" :current-page.sync="currentPage1" style="margin-top:20px"></el-pagination>
            </el-tab-pane>
            <el-tab-pane label="辅料" name="辅料">
                <el-row style="margin: 10px 0 20px 0">
                    <el-col :span="7">
                        <el-input placeholder="请输入关键词" style="width:300px" v-model.trim="searchName2">
                            <i slot="prefix" class="el-input__icon el-icon-search"></i>
                            <el-button slot="append" @click="handleSearch2">搜索</el-button>
                        </el-input>
                    </el-col>
                    <router-link :to="{path:'/materialCheck/addMaterialCheck',query: {type: '辅料'}}"><el-button type="primary" v-if="added" style="float:right; margin-right: 10px">添加原料</el-button></router-link>
					<el-button style="float:right; margin-right: 10px" @click="download">导出数据</el-button>
                </el-row>

                <el-table
                    :data="tableData"
                    border
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                >
                    <el-table-column prop="breedName" sortable label="名称"></el-table-column>
                    <el-table-column prop="inType" sortable label="入库类型"></el-table-column>
                    <el-table-column prop="inBatch" sortable label="进厂编号"></el-table-column>
                    <el-table-column prop="totalNum" sortable label="入库数量">
                        <template slot-scope="scope">
                            {{scope.row.totalNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="surplusNum" sortable label="剩余数量">
                        <template slot-scope="scope">
                            {{scope.row.surplusNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="lossNum" sortable label="报损数量">
                        <template slot-scope="scope">
                            {{scope.row.lossNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="car" sortable label="质量标准"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                v-if="check"
                                @click="handleView(scope.$index, scope.row)"
                            >查看</el-button>
                            <el-button type="text" v-if="scope.row.isRecall == 0">
                                <el-dropdown style="color: #409EFF; font-size:12px">
                                    <span class="el-dropdown-link">
                                        更多
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item>
                                            <el-button
                                                type="text"
                                                v-if="check1"
                                                @click="handleEdit(scope.$index, scope.row)"
                                                style="color: #666"
                                            >编辑</el-button>
                                        </el-dropdown-item>
										<el-dropdown-item>
										    <el-button
										        type="text"

										        @click="handleadd(scope.$index, scope.row)"
										        style="color: #666"
										    >新增入库</el-button>
										</el-dropdown-item>
                                        <el-dropdown-item>
                                            <el-button
                                                type="text"
                                                v-if="check2"
                                                @click="handleFrmLoss(scope.$index, scope.row)"
                                                style="color: #666"
                                            >报损</el-button>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </el-button>
                            <el-button
                                v-if="scope.row.isRecall == 1"
                                type="info"
                                disabled
                            >已召回</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize2" @current-change="handleCurrentChange2" :total="total2" :current-page.sync="currentPage2" style="margin-top:20px"></el-pagination>
            </el-tab-pane>
            <el-tab-pane v-if='!switchHeadTabOn' label="提取饮片" name="提取饮片">
                <el-row style="margin: 10px 0 20px 0">
                    <el-col :span="7">
                        <el-input placeholder="请输入关键词" style="width:300px" v-model.trim="searchName3">
                            <i slot="prefix" class="el-input__icon el-icon-search"></i>
                            <el-button slot="append" @click="handleSearch3">搜索</el-button>
                        </el-input>
                    </el-col>
                    <router-link :to="{path:'/materialCheck/addMaterialCheck',query: {type: '提取饮片'}}"><el-button type="primary" v-if="added" style="float:right; margin-right: 10px">添加原料</el-button></router-link>
					<el-button style="float:right; margin-right: 10px" @click="download">导出数据</el-button>
                </el-row>

                <el-table
                    :data="tableData"
                    border
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                >
                    <el-table-column prop="breedName" sortable label="名称"></el-table-column>
                    <el-table-column prop="inType" sortable label="入库类型"></el-table-column>
                    <el-table-column prop="inBatch" sortable label="进厂编号"></el-table-column>
                    <el-table-column prop="totalNum" sortable label="入库数量">
                        <template slot-scope="scope">
                            {{scope.row.totalNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="surplusNum" sortable label="剩余数量">
                        <template slot-scope="scope">
                            {{scope.row.surplusNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="lossNum" sortable label="报损数量">
                        <template slot-scope="scope">
                            {{scope.row.lossNum}}{{scope.row.units}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="car" sortable label="质量标准"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                v-if="check"
                                @click="handleView(scope.$index, scope.row)"
                            >查看</el-button>
                            <el-button type="text" v-if="scope.row.isRecall == 0">
                                <el-dropdown style="color: #409EFF; font-size:12px">
                                    <span class="el-dropdown-link">
                                        更多
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item>
                                            <el-button
                                                type="text"
                                                v-if="check1"
                                                @click="handleEdit(scope.$index, scope.row)"
                                                style="color: #666"
                                            >编辑</el-button>
                                        </el-dropdown-item>
										<el-dropdown-item>
										    <el-button
										        type="text"
										        @click="handleadd(scope.$index, scope.row)"
										        style="color: #666"
										    >新增入库</el-button>
										</el-dropdown-item>
                                        <el-dropdown-item>
                                            <el-button
                                                type="text"
                                                v-if="check2"
                                                @click="handleFrmLoss(scope.$index, scope.row)"
                                                style="color: #666"
                                            >报损</el-button>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </el-button>
                            <el-button
                                v-if="scope.row.isRecall == 1"
                                type="info"
                                disabled
                            >已召回</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize3" @current-change="handleCurrentChange3" :total="total3" :current-page.sync="currentPage3" style="margin-top:20px"></el-pagination>
            </el-tab-pane>
        </el-tabs>
        <el-dialog title="报损" :visible.sync="dialogFormVisible">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                <el-row style="margin: 10px 0 20px 0">
                    <el-col :span="16">
                        <el-form-item label="报损日期：" :label-width="formLabelWidth">
                            <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="ruleForm.time" style="width: 300px;"></el-date-picker>
                        </el-form-item>
                        <el-form-item label="报损数量：" prop="lossNum" :label-width="formLabelWidth">
                            <el-input v-model.number="ruleForm.lossNum"  @change="changeNum" style="width:300px">
                                <template slot="append">
                                    {{ruleForm.lossUnits}}
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="报损人：" prop="name" :label-width="formLabelWidth">
                            <el-input v-model.trim="ruleForm.name"  :disabled="disablede" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="报损原因：" :label-width="formLabelWidth">
                            <el-input type="textarea" v-model.trim="ruleForm.lossExplain" style="width:300px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
            </div>
        </el-dialog>
		<el-dialog title="新增入库" :visible.sync="dialogFormVisible1">
		    <el-form :model="ruleForm1" :rules="rules1" ref="ruleForm">
				<el-row style="margin: 10px 0 20px 0">
					<el-col :span="16">
						<el-form-item label="入库编号：" :label-width="formLabelWidth">
							<el-input v-model.trim="ruleForm1.inBatch"  :disabled="disablede" style="width:300px"></el-input>
						</el-form-item>
						<el-form-item label="入库日期：" :label-width="formLabelWidth">
							<el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="ruleForm1.inTime" @change = "get" style="width: 300px;"></el-date-picker>
						</el-form-item>
						<el-form-item label="入库数量：" prop="totalNum" :label-width="formLabelWidth">
							<el-input v-model.trim="ruleForm1.totalNum"   style="width:300px">
							</el-input>
							<span style="margin-left:20px;">{{ruleForm1.units}}</span>
						</el-form-item>
						<el-form-item label="操作人：" prop="name" :label-width="formLabelWidth">
							<el-input v-model.trim="ruleForm.name"  :disabled="disablede" style="width:300px"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
		    </el-form>
		    <div slot="footer" class="dialog-footer">
		        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
		        <el-button type="primary" @click="submitForm1('ruleForm')">确 定</el-button>
		    </div>
		</el-dialog>
    </div>
</template>

<script>
	import axios from 'axios'
import {material_findByList,user_findAll,loss_save,material_save} from "@/request/api";
    import bus from '@/components/common/bus';
    import { mapState } from 'vuex';
    export default {
        data() {
            return {
                switchHeadTabOn:false,
				dialogFormVisible1:false,
                disablede:true,
                dialogFormVisible: false,
                searchName1: '',
                searchName2: '',
                searchName3: '',
                activeName: '中药材',
                materialType: '中药材',
                tableData: [],
                total1: 0,
                currentPage1:1,
                pagesize1:10,
                total2: 0,
                currentPage2:1,
                pagesize2:10,
                total3: 0,
                currentPage3:1,
                pagesize3:10,
                ruleForm: {
                    name: '',
                    lossNum: '',
                    lossUnits: '',
                    lossExplain: ''
                },
				ruleForm1:{},
				rules1:{
					totalNum: [
					    { required: true, message: '不能为空', trigger: 'change' }
					]
				},
                rules:{
                    name: [
                        { required: true, message: '不能为空', trigger: 'change' }
                    ],
                    lossNum: [
                        { required: true, message: '不能为空', trigger: 'change' }
                    ]
                },
                formLabelWidth: '120px',
                userList: [],
                materialId: '',
                surplusNum: 0,
                added:true,
                check:true,
                check1:true,
                check2:true,
            };
        },
        created(){
            var data = JSON.stringify(this.$store.state.yl)
            var b = '新增'
            var a = '查看'
            var c = "编辑"
            var d = "报损"
            if(data.indexOf(b) != -1){
                this.added = true
            }else{
                this.added = false
            }

            if(data.indexOf(a) != -1){
                this.check = true
            }else{
                this.check = false
            }
            if(data.indexOf(c) != -1){
                this.check1 = true
            }else{
                this.check1 = false
            }
            if(data.indexOf(d) != -1){
                this.check2 = true
            }else{
                this.check2 = false
            }
        },
        computed:{
            ...mapState(['switchHeadTab'])
        },
        mounted(){
            this.ruleForm.userId = this.$store.state.userid
            this.ruleForm.name = this.$store.state.user
            if(this.$store.state.storName == '中药材'){
                this.activeName = '中药材'
                this.init1()
            } else if(this.$store.state.storName == '辅料'){
                this.activeName = '辅料'
                this.init2()
            } else if(this.$store.state.storName == '提取饮片'){
                this.activeName = '提取饮片'
                this.init3()
            } else{
                this.init1();
            }

            if(this.switchHeadTab == '生产系统'){
                this.switchHeadTabOn = false
            }else{
                this.switchHeadTabOn = true
            }
        },
        destroyed: function () {
            this.$store.commit("setStorName","")
        },
        methods: {

			download(){
				 axios({
				        method: 'GET',
				        url: '/material/out?materialType=' + this.activeName,

				        responseType: 'blob'
				    }).then(res=>{
				        // console.log(res)
				       this.downloadFile(res, '原料入库.xls')
				    }).catch(err=>{
				        // console.log(err)
				    })
			},
			downloadFile(res, fileName) {
			        let blob = new Blob([res.data]);
			        if (!fileName) {
			          fileName = res.headers['content-disposition'].split('filename=').pop();
			        }
			        if ('msSaveOrOpenBlob' in navigator) {
			          window.navigator.msSaveOrOpenBlob(blob, fileName);
			        } else {
			          const elink = document.createElement('a');
			          elink.download = fileName;
			          elink.style.display = 'none';
			          elink.href = URL.createObjectURL(blob);
			          document.body.appendChild(elink);
			          elink.click();
			          URL.revokeObjectURL(elink.href);
			          document.body.removeChild(elink);
			        }
			},
			get(ele){
				// console.log(111)
				// console.log(ele)
			},
			handleadd(index,row){
				this.ruleForm1.inBatch = row.inBatch
				this.ruleForm1.units = row.units
				// this.ruleForm1.inTime = new Date()
				this.dialogFormVisible1 = true
			},
			submitForm1(formName){

				this.$refs[formName].validate((valid) => {
				    if (valid) {
						this.ruleForm1.materialType = this.activeName
				        material_save(this.ruleForm1).then((res) => {
				            this.ruleForm = {}
				            this.$notify({
				                title: '提示',
				                message: '保存成功',
				                type: 'success',
				                duration:1000
				            });
				            this.dialogFormVisible1 = false
				            if (this.materialType == '中药材') {
				                this.init1()
				            } else if(this.materialType == '辅料') {
				                this.init2()
				            } else if(this.materialType == '提取饮片'){
				                this.init3()
				            }
				        })
				    } else {
				        return false;
				    }
				})
			},
            init(){
                user_findAll('').then((res)=>{
                    this.userList = res.data
                })
            },
            // 调用接口
            init1(){
              material_findByList({
                  materialType: '中药材',
                  searchName: this.searchName1,
                  page: this.currentPage1,
              }).then((res) =>{
                  this.tableData = res.rows
                  this.total1 = res.total
                  for (let i = 0; i < this.tableData.length; i++) {
                      if(this.tableData[i].qualityStandard){
                          this.tableData[i].car = this.tableData[i].qualityStandard.substring(0, 5) + "...."
                      }
                  }
              })
            },
            // 调用接口
            init2(){
              material_findByList({
                  materialType: '辅料',
                  searchName: this.searchName2,
                  page: this.currentPage2,
              }).then((res) =>{
                  this.tableData = res.rows
                  this.total2 = res.total
                    for (let i = 0; i < this.tableData.length; i++) {
                      if(this.tableData[i].qualityStandard){
                          this.tableData[i].car = this.tableData[i].qualityStandard.substring(0, 5) + "...."
                      }
                  }
              })
            },
            // 调用接口
            init3(){
              material_findByList({
                  materialType: '提取饮片',
                  searchName: this.searchName3,
                  page: this.currentPage3,
              }).then((res) =>{
                  this.tableData = res.rows
                  this.total3 = res.total
                    for (let i = 0; i < this.tableData.length; i++) {
                      if(this.tableData[i].qualityStandard){
                          this.tableData[i].car = this.tableData[i].qualityStandard.substring(0, 5) + "...."
                      }
                  }
              })
            },
            // tabs
            handleClick(tab, event) {
                this.materialType = tab.label
                if (this.materialType == '中药材') {
                    this.init1()
                } else if(this.materialType == '辅料') {
                    this.init2()
                } else if(this.materialType == '提取饮片'){
                    this.init3()
                }
            },
            //中药材编辑
            handleEdit(index,row){
                this.$router.push({
                    path: '/materialCheck/editMaterialCheck',
                    query: { id: row.id }
                });
            },
            // 查看
            handleView(index,row){
                this.$router.push({
                    path: '/materialCheck/viewMaterialCheck',
                    query: { id: row.id }
                });
            },
            //删除
            handleDelete1(index,row){
                this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$notify({
                        title: '操作成功',
                        message: '删除成功',
                        type: 'success'
                    });
                });
            },
            // 选择报损相关人
            // changeRelevant(ele){
            //     this.ruleForm.userId = ele.id
            //     this.ruleForm.name = ele.name
            // },
            // 中药材报损
            handleFrmLoss(index,row){
                this.init();
                this.dialogFormVisible = true
                this.ruleForm.materialId = row.id
                this.ruleForm.lossUnits = row.units
                this.surplusNum = parseInt(row.surplusNum)
            },
            changeNum(ele){
                if (ele <= 0) {
                    this.$notify.error({
                        title: '提示',
                        message: '报损数量不能为零或负数！',
                        showClose: false,
                        duration:2000
                    });
                    return this.ruleForm.lossNum = 0
                }
                if (ele > this.surplusNum) {
                    this.$notify.error({
                        title: '提示',
                        message: '报损数量不能大于剩余量！',
                        showClose: false,
                        duration:2000
                    });
                    return this.ruleForm.lossNum = 0
                }
            },
            // 提交报损
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        loss_save(this.ruleForm).then((res) =>{
                            this.ruleForm.lossNum = ""
                            this.ruleForm.lossExplain = ""
                            this.ruleForm.time = ""
                            this.$notify({
                                title: '提示',
                                message: '保存成功',
                                type: 'success',
                                duration:1000
                            });
                            this.dialogFormVisible = false
                            if (this.materialType == '中药材') {
                                this.init1()
                            } else if(this.materialType == '辅料') {
                                this.init2()
                            } else if(this.materialType == '提取饮片'){
                                this.init3()
                            }
                        })
                    } else {
                        return false;
                    }
                })
            },
            handleSearch1() {
                this.currentPage1 = 1
                this.init1()
            },
            handleSearch2() {
                this.currentPage2 = 1
                this.init2()
            },
            handleSearch3() {
                this.currentPage3 = 1
                this.init3()
            },
            handleCurrentChange1(val){
                this.currentPage1 = val
                this.init1()
            },
            handleCurrentChange2(val){
                this.currentPage2 = val
                this.init2()
            },
            handleCurrentChange3(val){
                this.currentPage3 = val
                this.init3()
            },
        }
    }
</script>

<style scoped>
.el-tabs__nav-wrap::after{
    background-color:#333333;
}
.el-pagination{
    text-align: center;
}
.el-col{
    margin-bottom: 0;
}
.el-select .el-input {
width: 130px;
}
.input-with-select .el-input-group__prepend {
background-color: #fff;
}
.el-input--small .el-input__inner{
    border-radius: 5px 0 0 5px !important;
    border-right: none;
}
</style>
